package com.example.ch07.preferences;

import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.ListPreference;
import androidx.preference.PreferenceFragmentCompat;

import com.example.ch07.R;

public class FlightPreferenceActivity extends AppCompatActivity implements
        SharedPreferences.OnSharedPreferenceChangeListener {
    public final static String[] optionText = getOptionText();
    public final static String[] optionValues = getOptionValues();
    static ListPreference listpref;

    static String[] getOptionText() {
        return new String[]{"Food", "Lounge", "Frequent Flier Program"};
    }

    static String[] getOptionValues() {
        return new String[]{"0", "1", "2"};
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(android.R.id.content, new MyPreferenceFragment())
                .commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
        listpref.getPreferenceManager().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
        setSummary();
    }

    @Override
    protected void onPause() {
        super.onPause();
        listpref.getPreferenceManager().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
        if ("selected_flight_sort_option".equals(key)) {
            setSummary();
        }
    }

    private void setSummary() {
        listpref.setSummary(optionText[Integer.valueOf(listpref.getValue())]);
    }

    public static class MyPreferenceFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.flightoptions01, rootKey);

            listpref = findPreference("selected_flight_sort_option");
            listpref.setEntryValues(optionValues);
            listpref.setEntries(optionText);
        }
    }
}
